package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.mapper.YddUserMapper;
import com.itheima.ydd.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.utils.JwtUtils;
import com.itheima.ydd.vo.*;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class YddUserServiceImpl extends ServiceImpl<YddUserMapper, YddUser> implements IYddUserService {

    @Autowired //配置
    private ISysConfigService sysConfigService;
    @Autowired //分类
    private IYddCateService yddCateService;
    @Autowired //标签
    private IYddTagService yddTagService;
    @Autowired //链接
    private IYddLinkService yddLinkService;
    @Autowired
    private IYddAdvimgService yddAdvimgService;

    //获取当前用户id
    public Integer getUserId(HttpServletRequest request){
        String token = request.getHeader("token");

        boolean flag = JwtUtils.verifyToken(token);
        if (!flag) {
            if (token == null){
                throw new BusinessException("用户未登录!");
            }
            throw new BusinessException("token已失效");
        }
        Claims claims = JwtUtils.getClaims(token);
        return (Integer) claims.get("userId");
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @Override
    public IndexVo selectIndex() {

        //按照 group_value 分组查询 group_value
        //select group_value,tab_value from sys_config group by group_value
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysConfig::getGroupValue, SysConfig::getTabValue)
                .groupBy(SysConfig::getGroupValue);
        List<SysConfig> list = sysConfigService.list(queryWrapper);

        //将 group_value 复制给ChildrenVo的name
        List<ChildrenVo> childrenVos = list.stream().map((config) -> {
            //SELECT * FROM sys_config WHERE group_value = ?
            //按 group_value 条件进行查找 可以查到 group_value 对应的所有数据
            LambdaQueryWrapper<SysConfig> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysConfig::getGroupValue, config.getGroupValue());
            List<SysConfig> list1 = sysConfigService.list(queryWrapper1);

            //将list1中查到 SysConfig 数据 添加到 ChildrenVo 中
            ChildrenVo childrenVo = new ChildrenVo();
            childrenVo.setName(config.getGroupValue());
            childrenVo.setData(list1);

            return childrenVo;
        }).collect(Collectors.toList());

        //按照 tab_value 分组查询 tab_value
        //select group_value,tab_value from sys_config group by tab_value
        LambdaQueryWrapper<SysConfig> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.select(SysConfig::getGroupValue, SysConfig::getTabValue)
                .groupBy(SysConfig::getTabValue);
        List<SysConfig> list2 = sysConfigService.list(queryWrapper2);

        //将list里的 group_value,tab_value 数据添加到 SysConfigVo 中
        List<SysConfigVo> sysConfigVos = list2.stream().map((item) -> {
            SysConfigVo sysConfigVo = new SysConfigVo();
            sysConfigVo.setKey(item.getTabValue());

            if (item.getTabValue().equals("base")) {
                sysConfigVo.setName("基础配置");
            } else if (item.getTabValue().equals("system")) {
                sysConfigVo.setName("系统设置");
            } else {
                sysConfigVo.setName("其他设置");
            }

            ArrayList<ChildrenVo> sysConfigs = new ArrayList<>();
            for (ChildrenVo sysConfig : childrenVos) {
                for (SysConfig data : sysConfig.getData()) {
                    if (data.getTabValue().equals(item.getTabValue())) {
                        sysConfigs.remove(sysConfig);
                        //将数据封装到 sysConfigs 中
                        sysConfigs.add(sysConfig);
                    }
                }
            }
            if (sysConfigs.toString() != null) {
                sysConfigVo.setChildren(sysConfigs);
            }

            return sysConfigVo;
        }).collect(Collectors.toList());



        //allData
        List<SysConfig> configs = sysConfigService.list();

        //封装收集的数据添加到 返回数据的对象中
        Map<String, List> map = new HashMap<>();
        map.put("list", sysConfigVos);
        map.put("allData", configs);

        //查询所有分类
        List<YddCate> allCate = yddCateService.list();

        //查询所有标签
        List<YddTag> allTAg = yddTagService.list();

        //查询所有友情链接（文字和图片）
        List<YddLink> allLink = yddLinkService.list();

        //查询yddA_dvimg
        List<YddAdvimg> yddAdvimgList = yddAdvimgService.list();

        List<YddAdvimg> showBanner = new ArrayList<>();
        List<YddAdvimg> sideBanner = new ArrayList<>();
        List<YddAdvimg> banner = new ArrayList<>();

        for (YddAdvimg yddAdvimg : yddAdvimgList) {
            String advimgpos = yddAdvimg.getAdvimgpos();

            switch (advimgpos) {
                case "12":
                    showBanner.add(yddAdvimg);//查询详情广告图
                    break;
                case "13":
                    sideBanner.add(yddAdvimg);//查询详情广告图
                    break;
                case "14":
                    sideBanner.add(yddAdvimg);//查询侧边栏图片
                    break;
                case "15":
                    banner.add(yddAdvimg);//轮播图数据
                    break;
                default:
                    showBanner.add(yddAdvimg);//查询详情广告图
            }
        }

        //返回数据对象
        IndexVo indexVo = new IndexVo();
        indexVo.setAllCate(allCate);
        indexVo.setConfig(map);
        indexVo.setAllTAg(allTAg);
        indexVo.setAllLink(allLink);
        indexVo.setBanner(banner);
        indexVo.setShowBanner(showBanner);
        indexVo.setSideBanner(sideBanner);

        return indexVo;
    }
}
